package com.okaixz.client.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.okaixz.client.mapper.UserMapper;
import com.okaixz.client.model.domain.*;
import com.okaixz.client.model.dto.*;
import com.okaixz.client.service.*;
import com.okaixz.client.utils.AES256Util;
import com.okaixz.client.utils.SensitiveWordUtil;
import com.okaixz.common.client.exception.BusinessException;
import com.okaixz.common.client.exception.CommonErrorCode;
import com.okaixz.common.constant.CommonConstants;
import com.okaixz.common.constant.RedisConstants;
import com.okaixz.common.constant.UserConstants;
import com.okaixz.common.core.redis.RedisCache;
import com.okaixz.common.utils.StringUtils;
import com.okaixz.manager.utils.BaseContext;
import com.okaixz.manager.utils.MyIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author cdz
 * @since 2024-10-08
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    public StringRedisTemplate redisTemplate;
    @Autowired
    private ITokenService tokenService;
    @Autowired
    private IKbUserAssistantInfoService kbUserAssistantInfoService;
    @Autowired
    private IKbUserAssistantInfoNewService userAssistantInfoServiceNew;
    @Autowired
    private IKbAssistantService kbAssistantService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IShareInfoService shareInfoService;
    @Autowired
    private ITaskInfoService taskInfoService;
    @Autowired
    private IWxService wxService;

    @Autowired
    private MyIdUtil myIdUtil;


    @Override
    public UserDto fillVipFlag(UserDto user) {
        if (user == null) {
            return null;
        }
        LocalDateTime vipExpireTime = user.getVipExpireTime();
        LocalDateTime vipExpireTime1 = user.getVipExpireTime1();
        Integer vipTokens = user.getVipTokens();
        LocalDateTime now = LocalDateTime.now();
        if (vipExpireTime1 != null && vipExpireTime1.isAfter(now)) {
            user.setVipFlag(CommonConstants.VIP_FLAG_FREE_TOKENS_VIP);
        } else if (vipExpireTime != null && vipExpireTime.isAfter(now)) {
            if (vipTokens != null && vipTokens > 0) {
                user.setVipFlag(CommonConstants.VIP_FLAG_LIMIT_TOKENS_VIP);
            } else {
                user.setVipFlag(CommonConstants.VIP_FLAG_LIMIT_TOKENS_NO_TOKENS);//字数不够
            }
        } else {
            user.setVipFlag(CommonConstants.VIP_FLAG_NOT_VIP);
        }
        //其它信息
        user.setOtherInfo(getOtherInfo(user.getVipFlag()));
        log.info("checkVip vipflag={}", user.getVipFlag());
        return user;
    }

    public String getOtherInfo(Integer vipFlag){
        //其它信息一年中第几天三位 然后将vipFlag插入到第3位 总共四位
        String dayOfYear = myIdUtil.getDayOfYear();
        StringBuilder sb=new StringBuilder(dayOfYear);
        sb.insert(2, vipFlag);
        return AES256Util.encryptUser(sb.toString(),"");
    }

    public User fillVipFlag(User user) {
        if (user == null) {
            return null;
        }
        LocalDateTime vipExpireTime = user.getVipExpireTime();
        LocalDateTime vipExpireTime1 = user.getVipExpireTime1();
        Integer vipTokens = user.getVipTokens();
        Integer remainTimes = user.getRemainTimes();
        LocalDateTime now = LocalDateTime.now();
        if (vipExpireTime1 != null && vipExpireTime1.isAfter(now)) {
            user.setVipFlag(CommonConstants.VIP_FLAG_FREE_TOKENS_VIP);
        } else if (vipExpireTime != null && vipExpireTime.isAfter(now)) {
            if (vipTokens != null && vipTokens > 0) {
                user.setVipFlag(CommonConstants.VIP_FLAG_LIMIT_TOKENS_VIP);
            } else {
                user.setVipFlag(CommonConstants.VIP_FLAG_LIMIT_TOKENS_NO_TOKENS);//字数不够
            }
        } else if (remainTimes != null && remainTimes > 0) {
            user.setVipFlag(CommonConstants.VIP_FLAG_LIMIT_TIMES_VIP);
        } else {
            user.setVipFlag(CommonConstants.VIP_FLAG_NOT_VIP);
        }

        //其它信息
        user.setOtherInfo(getOtherInfo(user.getVipFlag()));

        log.info("checkVip vipflag={}", user.getVipFlag());
        return user;
    }


    @Override
    public void reduceRemainTimes(UserDto userDto) {
        Integer remainTimes = userDto.getRemainTimes();
        if (remainTimes != null && remainTimes > 0) {
            userDto.setRemainTimes(remainTimes - 1);
            User user = new User();
            BeanUtils.copyProperties(userDto, user);
            log.info("remainTimes=" + user.getRemainTimes());
            updateUserByUserId(user);
        }
    }

    @Override
    public void reduceTokens(UserDto userDto, int reduceTokens) {
        Integer vipTokens = userDto.getVipTokens();
        if (vipTokens == null) {
            return;
        }
        vipTokens = vipTokens - reduceTokens;
        User user = getUserFormRedisOrDb(userDto.getUserId());
        if (user == null) {
            return;
        }
        user.setVipTokens(vipTokens);
        userDto.setVipTokens(vipTokens);
        updateUserByUserId(user);
    }

    @Override
    @Transactional
    public boolean updateUserByUserId(User user) {
        if (user == null) {
            return false;
        }
        user = fillVipFlag(user);//更新vip标志
        user.setUpdateTime(LocalDateTime.now());
        boolean update = lambdaUpdate()
                .eq(User::getUserId, user.getUserId())
                .update(user);
        if (update) {
            user = lambdaQuery()
                    .eq(User::getUserId, user.getUserId())
                    .one();
            saveUserToRedis(user);//更新缓存中的用户信息 会更新user中的vip标志
        }
        return update;
    }

    @Override
    public UserDto updateUserInfoByUserId(UpdateUserDto updateUserDto) {
        if (updateUserDto == null) {
            return null;
        }
        String nickName = updateUserDto.getNickName();
        boolean contains = SensitiveWordUtil.contains(nickName);
        if (contains) {
            throw new BusinessException(CommonErrorCode.SENSITIVE_WORDS);
        }

        User user = getUserFormRedisOrDb(updateUserDto.getUserId());
        BeanUtils.copyProperties(updateUserDto, user);
        boolean result = updateUserByUserId(user);
        if (result) {
            UserDto userDto = kbGetUserinfoById(updateUserDto.getUserId());
            return userDto;
        }
        return null;
    }

    @Override
    public UserDto kbGetUserinfoById(String userId) {
        UserDto userDto = getUserDtoFormRedisOrDb(userId);

        Integer sex = userDto.getSex();
        if (sex != null) {
            //查询用户添加的标签
            int httpVersion = BaseContext.getHttpVersion();
            if(httpVersion>=1){
                List<KbAssistant> kbAssistantList = userAssistantInfoServiceNew.getAssistantByUserIdAndSex(userId, sex);
                userDto.setAssistantList(kbAssistantList);
            }else {
                List<KbUserAssistantInfo> listbyUserId = kbUserAssistantInfoService.getListbyUserId(userId, sex);
                userDto.setUserAssistantInfoList(listbyUserId);
            }
        }

        return userDto;
    }

    @Override
    public UserDto updateUserInfoByUserId(UserDto userDto) {
        User user = getUserFormRedisOrDb(userDto.getUserId());
        BeanUtils.copyProperties(userDto, user);
        boolean result = updateUserByUserId(user);
        if (result) {
            UserDto resultUserDto = kbGetUserinfoById(userDto.getUserId());
            return resultUserDto;
        }
        return null;
    }

    @Override
    public UserDto updateUserInfoByUserId(User user) {
        boolean result = updateUserByUserId(user);
        if (result) {
            UserDto resultUserDto = kbGetUserinfoById(user.getUserId());
            return resultUserDto;
        }
        return null;
    }

    @Override
    public UserDto kbUpdateUserSex(UpdateUserDto updateUserDto) {
        User user = getUserFormRedisOrDb(updateUserDto.getUserId());
        BeanUtils.copyProperties(updateUserDto, user);
        boolean result = updateUserByUserId(user);
        if (result) {
            UserDto userDto = kbGetUserinfoById(updateUserDto.getUserId());
            return userDto;
        }
        return null;
    }

    @Override
    public boolean saveOrUpdateUser(User user) {
        if (user == null) {
            return false;
        }
        user = fillVipFlag(user);
        boolean saveOrUpdate = saveOrUpdate(user);
        if (saveOrUpdate) {
            saveUserToRedis(user);//更新缓存中的用户信息
        }
        return saveOrUpdate;
    }

    @Override
    public UserDto saveHead(UserDto userDto) {
        String image = userDto.getImage();

        return null;
    }

    @Override
    public String wxQrcode() {
        String appid = "";
        String redirect_uri = "";
        String response_type = "code";
        String scope = "snsapi_userinfo";
        String state = "666";
        StringBuilder sb = new StringBuilder();
        sb.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
        sb.append(appid);
        sb.append("&redirect_uri=");
        sb.append(redirect_uri);
        sb.append("&response_type=");
        sb.append(response_type);
        sb.append("&scope=");
        sb.append(scope);
        sb.append("&state=");
        sb.append(state);
        sb.append("#wechat_redirect");

        return sb.toString();
    }

    @Override
    @Transactional
    public UserDto updateVipInfo(Integer gid, String userId) {
        Goods goods = goodsService.getById(gid);
        if (goods == null) {
            return null;
        }
        User user = getUserFormRedisOrDb(userId);
        if (user == null) {
            return null;
        }
        Integer tokens = goods.getToken();
        Integer expireDays = goods.getExpireDays();//有效天数
        Integer type = goods.getType();
        LocalDateTime vipExpireTime = null;
        Integer vipTokens = null;
        switch (type) {
            case 1://会员充值
                //更新会员过期时间
                vipExpireTime = user.getVipExpireTime();
                if (vipExpireTime == null || vipExpireTime.isBefore(LocalDateTime.now())) {
                    //已过期或未开通会员
                    user.setVipExpireTime(LocalDateTime.now().plusDays(expireDays));
                } else {
                    //原来未过期
                    user.setVipExpireTime(vipExpireTime.plusDays(expireDays));
                }

                //更新会员写作剩余字数
                vipTokens = user.getVipTokens();
                if (vipTokens == null) {
                    vipTokens = 0;
                }
                user.setVipTokens(vipTokens + tokens);
                break;
            case 2://不限字数充值
                //更新不限字数会员过期时间
                LocalDateTime vipExpireTime1 = user.getVipExpireTime1();
                if (vipExpireTime1 == null || vipExpireTime1.isBefore(LocalDateTime.now())) {
                    //已过期或未开通会员
                    user.setVipExpireTime1(LocalDateTime.now().plusDays(expireDays));
                } else {
                    //原来未过期
                    user.setVipExpireTime1(vipExpireTime1.plusDays(expireDays));
                }
                break;
            case 0://字数充值
                //更新会员写作剩余字数
                vipTokens = user.getVipTokens();
                if (vipTokens == null) {
                    vipTokens = 0;
                }
                user.setVipTokens(vipTokens + tokens);
                break;
            case 3://激励视频奖励
                //更新会员剩余使用次数
                Integer remainTimes = user.getRemainTimes();
                if (remainTimes == null) {
                    remainTimes = 0;
                }
                user.setRemainTimes(remainTimes + tokens);
                break;
            default:
                break;
        }
        boolean updateResult = updateUserByUserId(user);//更新数据库和缓存中的用户信息
        log.info("更新用户vip信息 结果：{}", updateResult);
        if (!updateResult) {
            return null;
        }
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        fillVipFlag(userDto);
        return userDto;
    }

    @Override
    @Transactional
    public UserDto updateVipExpireTime(Integer value, String userId) {
        User user = getUserFormRedisOrDb(userId);
        if (user == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        //更新不限字数会员过期时间
        LocalDateTime vipExpireTime1 = user.getVipExpireTime1();
        if (vipExpireTime1 == null || vipExpireTime1.isBefore(LocalDateTime.now())) {
            //已过期或未开通会员
            user.setVipExpireTime1(LocalDateTime.now().plusDays(value));
        } else {
            //原来未过期
            user.setVipExpireTime1(vipExpireTime1.plusDays(value));
        }

        boolean updateResult = updateUserByUserId(user);//更新数据库和缓存中的用户信息
        log.info("更新用户vip信息 结果：{}", updateResult);
        if (!updateResult) {
            return null;
        }
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        fillVipFlag(userDto);
        return userDto;
    }

    @Override
    public User getUserByUserIdFromDB(String userId) {
        if (userId == null) {
            return null;
        }
        User user = lambdaQuery()
                .eq(User::getUserId, userId)
                .one();
        fillVipFlag(user);
        fillNaoid(user);
        return user;
    }


    @Override
    public User getUserFormRedisOrDb(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        User user = getUserFromRedis(userId);
        if (user == null) {
            user = getUserByUserIdFromDB(userId);
        }
//        if (user!= null) {
//            String password = user.getPassword();
//            if (StringUtils.isNotEmpty(password)) {
//                password=AES256Util.decryptDb(password);//解密密码得到原始密码
//                user.setPassword(AES256Util.encryptUser(password, ""));//用客户端密钥加密
//            }
//        }
        return user;
    }

    @Override
    public UserDto getUserDtoFormRedisOrDb(String userId) {
        User user = getUserFormRedisOrDb(userId);
        if (user != null) {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            return userDto;
        }
        return null;
    }

    @Override
    public User getUserFromRedis(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        String key = RedisConstants.USER_KEY_PREF + userId;
        User user = redisCache.getCacheObject(key);
        user = fillVipFlag(user);
        return user;
    }

    /**
     * 保存用户信息到redis缓存
     *
     * @param user
     */
    @Override
    public void saveUserToRedis(User user) {
        user = fillNaoid(user);
        user = fillVipFlag(user);
        String key = RedisConstants.USER_KEY_PREF + user.getUserId();


        User userNew = new User();
        BeanUtils.copyProperties(user, userNew);
        //去除不需要保存到redis的属性
        userNew.setImage(null);
        userNew.setWxAccessToken(null);
        userNew.setWxRefreshToken(null);
        userNew.setUpdateTime(LocalDateTime.now());

        redisCache.setCacheObject(key, userNew);
//        redisCache.setHashObject(key, user);
    }

    @Override
    public void removeUserFromRedis(String userId) {
        String key = RedisConstants.USER_KEY_PREF + userId;
        redisCache.deleteObject(key);
    }

    @Override
    public UserDto saveOrUpdateUser(String openId, Integer subscribe) {
        if (openId == null) {
            return null;
        }
        User user = lambdaQuery()
                .eq(User::getWxOpenid, openId)
                .eq(User::getType, CommonConstants.USER_TYPE_PC)
                .one();
        if (user == null) {
            //用户不存在
            user = new User();
            //            String simpleUUID = IdUtil.nanoId();
            String simpleUUID = myIdUtil.getUserId();
            user.setUserId(simpleUUID);
            user.setCreatedTime(LocalDateTime.now());
            user.setNickName("微信用户");
            user.setVipTokens(3000);
            user.setType(CommonConstants.USER_TYPE_PC);
            user.setVipExpireTime(LocalDateTime.now().plusDays(3));
        }
        user.setUpdateTime(LocalDateTime.now());
        user.setWxOpenid(openId);
        if (subscribe != null) {
            user.setSubscribe(subscribe);
        }
        saveOrUpdateUser(user);

//        UserDto userDto = tokenService.refreshUserAndToken(user.getUserId());
        UserDto userDto = getUserDtoFormRedisOrDb(user.getUserId());

        //生成6位数字id 要求id唯一

        return userDto;
    }

    @Override
    public UserDto wxMiniprogramLogin(String openid, String sessionKey, String shareUserId) {
        User user = null;
        try {
            user = lambdaQuery()
                    .eq(User::getWxOpenid, openid)
                    .eq(User::getType, CommonConstants.USER_TYPE_MINPROGRAM)
                    .one();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user == null) {
            //用户不存在向用户表中插入用户数据
            user = new User();
            //            String simpleUUID = IdUtil.nanoId();
            String simpleUUID = myIdUtil.getUserId();
            user.setUserId(simpleUUID);
            user.setWxOpenid(openid);
            user.setWxSessionKey(sessionKey);
            user.setCreatedTime(LocalDateTime.now());
            user.setNickName("微信用户");
            user.setType(CommonConstants.USER_TYPE_MINPROGRAM);
            user.setVipTokens(3000);
            user.setVipExpireTime(LocalDateTime.now().plusDays(3));

            if (StringUtils.isNotEmpty(shareUserId)) {
                ShareInfo shareInfo = shareInfoService.saveShareInfo(user, shareUserId);
                updateVipInfo(9, shareUserId);
            }

        } else {
            //更新sessikonkey
            user.setWxSessionKey(sessionKey);
            user.setWxOpenid(openid);
            user.setUpdateTime(LocalDateTime.now());
            //            updateById(user);
        }
        saveOrUpdateUser(user);
        UserDto userDto = tokenService.refreshUserAndToken(user.getUserId());
        return userDto;
    }

    @Override
    public User fillNaoid(User user) {
        if (user == null) {
            return null;
        }
        //如果用户信息中不存在nanoid 将缓存中的nanoid设置到用户信息中
        if (StringUtils.isEmpty(user.getNanoid())) {
            User userFromRedis = getUserFromRedis(user.getUserId());
            if (userFromRedis != null) {
                user.setNanoid(userFromRedis.getNanoid());
            }
        }
        return user;
    }

    @Override
    public User processWxQrcodeLoginCallBack(String openid, String access_token, String refresh_token, String headimgurl, String nickname) {
        User user = lambdaQuery()
                .eq(User::getWxOpenid, openid)
                .eq(User::getType, CommonConstants.USER_TYPE_PC)
                .one();
        if (user == null) {
            //用户不存在
            user = new User();
            //            String simpleUUID = IdUtil.nanoId();
            String simpleUUID = myIdUtil.getUserId();
            user.setUserId(simpleUUID);
            user.setCreatedTime(LocalDateTime.now());
        }
        user.setUpdateTime(LocalDateTime.now());
        user.setWxOpenid(openid);
        user.setWxAccessToken(access_token);
        user.setWxRefreshToken(refresh_token);
        user.setImage(headimgurl);
        user.setNickName(nickname);
        boolean result = saveOrUpdateUser(user);
        if (!result) {
            return null;
        }
        return user;
    }


    @Override
    public UserDto wxLogin(GetAccessTokenParams params) {
        String clientName = params.getClientName();
        WxAccessTokenResult accessToken = wxService.getAccessToken(params);
        if (accessToken == null) {
            return null;
        }
        WxUserInfo userInfo = wxService.getUserInfo(accessToken.getAccess_token(), accessToken.getOpenid());

        User user = getOrCreateUserByWxOpenId(clientName, userInfo, accessToken);

        clientName = user.getClientName();

        UserDto userDto = null;
        switch (clientName) {
            case CommonConstants.AIKEYBOARD:
                userDto = kbGetUserinfoById(user.getUserId());
                if (userDto != null) {
                    UserDto tokenUser = tokenService.refreshUserAndToken(user.getUserId());
                    userDto.setToken(tokenUser.getToken());
                }
                break;
            case CommonConstants.MOEDOKILOCK:
                userDto = tokenService.refreshUserAndToken(user.getUserId());
                break;
            case CommonConstants.PWDINPUT:
                userDto = tokenService.refreshUserAndToken(user.getUserId());
                break;
        }

        return userDto;
    }


    /**
     * 根据微信openid和客户端名称查询或创建用户 当用户不存在时创建用户
     *
     * @return
     */
    @Override
    public User getOrCreateUserByWxOpenId(String clientName, WxUserInfo userInfo, WxAccessTokenResult accessToken) {
//        User user = lambdaQuery()
//                .eq(User::getWxOpenid, userInfo.getOpenid())
//                .eq(User::getClientName, clientName)
//                .eq(User::getStatus, UserConstants.USER_STATUS_NORMAL)
//                .one();
        User user = lambdaQuery()
                .eq(User::getWxOpenid, userInfo.getOpenid())
                .eq(User::getClientName, clientName)
                .one();

        if (user == null) {
            //用户不存在
            String userId = myIdUtil.getUserId();
            user = new User();
            user.setUserId(userId);
            user.setCreatedTime(LocalDateTime.now());
            user.setClientName(clientName);
            user.setImage(userInfo.getHeadimgurl());
            user.setNickName(userInfo.getNickname());

            TaskInfo taskInfo = taskInfoService.getEnableTaskInfoByClientNameAndType(CommonConstants.TASK_TYPE_NEW_USER_REGISTER,  clientName);
            if (taskInfo != null) {
                Integer flag = taskInfo.getFlag();
                Integer plusValue = taskInfo.getPlusValue();
                switch (flag) {
                    case CommonConstants.TASK_FLAG_0://增加试用次数
                        //给用户发放试用次数
                        user.setRemainTimes(plusValue);
                        break;
                    case CommonConstants.TASK_FLAG_1://增加会员天数
                        //给用户发放会员天数;
                        user.setVipExpireTime1(LocalDateTime.now().plusDays(plusValue));
                        break;
                    case 2:

                        break;
                }
            }

        } else if (user.getStatus() == UserConstants.USER_STATUS_LOGOFF) {
            throw new BusinessException(CommonErrorCode.USER_LOGOFF);
        }

        user.setUpdateTime(LocalDateTime.now());
        user.setWxOpenid(userInfo.getOpenid());
        user.setWxAccessToken(accessToken.getAccess_token());
        user.setWxRefreshToken(accessToken.getRefresh_token());
        boolean result = saveOrUpdateUser(user);
        if (!result) {
            return null;
        }
        return user;
    }

    @Override
    public boolean logoffByUserId(String userId) {
        User user = getUserFormRedisOrDb(userId);
        if (user == null) {
            //用户不存在
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        removeUserFromRedis(userId);//删除用户缓存

        user.setStatus(UserConstants.USER_STATUS_LOGOFF);
        boolean result = saveOrUpdate(user);
        return result;
    }


    @Override
    public User getUserByUserIdAndClientName(String clientName, String userId) {
        if (clientName == null || userId == null) {
            return null;
        }
        User user = getUserFormRedisOrDb(userId);
        if (user == null) {
            return null;
        }
        String clientName1 = user.getClientName();
        if (clientName1 != null && clientName1.equals(clientName)) {
            return user;
        }
        return null;
    }

    @Override
    public boolean resetQiandao() {
        //重置数据库签到值为0
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.set(User::getQiandao, 0);
        boolean update = update(lambdaUpdateWrapper);

        //重置缓存签到值为0
        redisCache.batchUpdateQianDaoByLua();
        return update;
    }

    @Override
    public boolean updatePwd(String pwdNew, String pwdOld, String userId) {
        User user = getUserFormRedisOrDb(userId);
        if (user == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        String password = user.getPassword();
        password= AES256Util.decryptDb(password);

        if (StringUtils.isNotEmpty(pwdOld)) {
            //旧密码不为空是修改密码 需要验证旧密码是否正确
            if (StringUtils.isEmpty(password)) {
                password="";
            }
            pwdOld=AES256Util.decryptUser(pwdOld,"");
            log.info("旧密码：{}",pwdOld);
            log.info("旧密码db：{}",password);
            if (!password.equals(pwdOld)) {
                throw new BusinessException(CommonErrorCode.PWD_ERROR);
            }
        }

        pwdNew=AES256Util.decryptUser(pwdNew,"");
        pwdNew=AES256Util.encryptDb(pwdNew);
        user.setPassword(pwdNew);

        boolean result = updateUserByUserId(user);
        return result;
    }

    @Override
    public Integer checkPwd(String pwd) {
        String userId = BaseContext.getUserId();
        User user = getUserFormRedisOrDb(userId);
        if (user == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        String key = RedisConstants.PWD_CHECK_ERROR_KEY_PREF + userId;
        String errorTimes = redisTemplate.opsForValue().get(key);
        log.info("errorTimes:{}",errorTimes);
        Long errorTimesL= errorTimes == null ? 0 : Long.parseLong(errorTimes);
        if(errorTimesL>=CommonConstants.PWD_CHECK_MAX_RETRY_TIMES){
//            throw new BusinessException(CommonErrorCode.PWD_ERROR_TOO_MANY_TIMES);
            return 0;
        }


        String password = user.getPassword();
        if (password == null) {
            throw new BusinessException(CommonErrorCode.PWD_NOT_SET_ERROR);
        }
        password= AES256Util.decryptDb(password);//解密得到原始密码

        pwd=AES256Util.decryptUser(pwd,"");//解密得到原始密码
        if (password.equals(pwd)) {
            redisTemplate.delete(key);
            return 10;
        }
        Long increment = redisTemplate.opsForValue().increment(key);
        log.info("increment:{}",increment);
//        if(increment==CommonConstants.PWD_CHECK_MAX_RETRY_TIMES){
//            redisTemplate.expire(key, 60, TimeUnit.MINUTES);
//        }else {
//            redisTemplate.expire(key, 60, TimeUnit.MINUTES);
//        }
        redisTemplate.expire(key, 60, TimeUnit.MINUTES);

        return CommonConstants.PWD_CHECK_MAX_RETRY_TIMES-increment.intValue();
    }

    @Override
    public Integer updateFlag(Integer flag) {
        User user = getTokenUser();
        user.setFlag(flag);
        updateUserInfoByUserId( user);
        return flag;
    }

    @Override
    public User getTokenUser() {
        String userId = BaseContext.getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        User user = getUserFormRedisOrDb(userId);
        if (user == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        return user;
    }




}
